package com.gwc.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;


public class ServletConfigTest extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletConfig servletConfig = this.getServletConfig();
        // 根据参数名获取单个参数
        String param1Value = servletConfig.getInitParameter("param1");
        System.out.println("param1: "+param1Value);
        // 获取所有参数名
        Enumeration<String> initParameterNames = servletConfig.getInitParameterNames();
        while (initParameterNames.hasMoreElements()){
            String paramaterName = initParameterNames.nextElement();
            System.out.println(paramaterName+":"+servletConfig.getInitParameter(paramaterName));
        }

        // 测试ServletContext
        ServletContext servletContext = servletConfig.getServletContext();
        ServletContext servletContext1 = req.getServletContext();
        ServletContext servletContext2 = this.getServletContext();
        System.out.println(servletContext==servletContext1);
        System.out.println(servletContext1==servletContext2);
        Enumeration<String> initParameterNames1 = servletContext.getInitParameterNames();
        while (initParameterNames1.hasMoreElements()){
            String contextInit = initParameterNames1.nextElement();
            System.out.println(contextInit+":"+servletContext.getInitParameter(contextInit));

        }

        // ServletContext其他重要的API
        // 获得一个指向项目部署位置下的某个文件/目录的磁盘真实路径
        String uploadPath = servletContext.getRealPath("upload");
        System.out.println(uploadPath);

        // 获取项目部署的上下文路径 项目的访问路径
        String contextPath = servletContext.getContextPath();
        System.out.println(contextPath);
    }
}
